import axios from 'axios'
import store from '@/store/index.js'
import router from '@/router/index.js'
const request = axios.create({
  // baseURL: 'http://ttapi.research.itcast.cn/'
  // baseURL: 'http://toutiao.itheima.net'
  baseURL: 'https://toutiao.itheima.net'
})
// 通过请求拦截器,每次发请求都添加token
// 请求拦截器写法1-复制文档
// 请求拦截器写法2-通过代码片段
// (1)安装扩展-Axios Snippets
// (2)查看代码片段的使用方式-C:\Users\当前用户\.vscode\extensions\yggdrasill-7c9.axios-snippets-1.0.0
// (3)看拦截器的缩写,"prefix": "axios.interceptors.request.use",
request.interceptors.request.use(config => {
// Do something before request is sent
  if (store.state.token) {
    config.headers.Authorization = 'Bearer ' + store.state.token
  }
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})

// 通响应拦截器-后台报401,直接跳转到登录页面
request.interceptors.response.use(response => {
  // 如果成功执行这个成功的回调
// Do something before response is sent

  return response
}, error => {
  console.log(error)
  // 如果成功执行这个失败的的回调
  if (error.response && error.response.status === 401) {
    router.push('/login')
  }
  // Do something with response error
  return Promise.reject(error)
})
export default request
